<#import "/macro.ftl" as m>
<@m.page_header title='后台' />
<script type="text/javascript" src="/assets/ueditor/ueditor.config.js"></script>
<script type="text/javascript" src="/assets/ueditor/ueditor.all.js"></script>
<script type="text/javascript" src="/assets/ueditor/lang/zh-cn/zh-cn.js"></script>
<script type="text/javascript" src="/assets/js/md5.js"></script>

<div id="page-content-wrapper">

<div id="page-title">

    <h3>
    <#if product>修改产品<#else>添加产品</#if>
        <small>
            类资产项目
        </small>
    </h3>
</div>
<div class="pad10A">
<#if product>
<form id="demo-form1" action="/products/update/${product.serial}" class="col-md-12" method="POST">
<input type="hidden" name="id" value="${((product.id)!'')?xhtml}"/>
<#else>
<form id="demo-form1" action="/products/add" class="col-md-12" method="POST">
</#if>
<div class="form-row">
    <div class="form-label col-md-2">
        <label for="">
            产品类别:
            <span class="required">*</span>
        </label>
    </div>
    <div class="form-input col-md-8">
	    <#if product.id??>
			<#if product.category??>
				<div class="form-label col-md-2">
			        <label>${product.categoryName}</label>
			    </div>
			    <input type="hidden" id="category" name="category" value="${product.category}">
			</#if>
		<#else>
	    	<select id="category" name="category" onchange="onCategoryChanged();">
		    	<option value="TRANSFER" <#if product.category == 'TRANSFER'>selected</#if> >债转</option>
		    	<option value="MONTH" <#if product.category == 'MONTH'>selected</#if> >月享</option>
		    	<option value="DOUBLE" <#if product.category == 'DOUBLE'>selected</#if> >双月享</option>
		    	<option value="SEASON" <#if product.category == 'SEASON'>selected</#if> >季享</option>
		    	<option value="MONTHSEASON" <#if product.category == 'MONTHSEASON'>selected</#if> >月季享</option>
		    </select>
		</#if>
    </div>
</div>
<div class="form-row">
    <div class="form-label col-md-2">
        <label for="">
            产品名称:
            <span class="required">*</span>
        </label>
    </div>
    <div class="form-input col-md-8">
        <input type="text" id="name" name="name" data-trigger="change" data-required="true" class="parsley-validated"
               value="${((product.name)!'')?xhtml}">
    </div>
</div>
    <#--

<div class="form-row">
    <div class="form-label col-md-2">
        <label for="financialAsset">
            金融资产:
        </label>
    </div>
	<#if product.id??>
		<div class="form-label col-md-8">
			<#if product.financialAsset??>
				<label>${product.financialAsset.name} 到期日：${product.financialAsset.dueDate?string('yyyy-MM-dd')}</label>
			</#if>
		</div>
	<#else>
    	<div class="form-input col-md-8">
	    	<select id="financialAsset" name="financialAsset.id">
	        	<option value="" <#if product.financialAsset??==false>selected</#if> >金融资产产品，请选择相应的金融资产。不是，则不选。</option>
	        	<#list financialAssets as financialAsset>
	        		<option value="${financialAsset.id}" <#if product.financialAsset.id == financialAsset.id >selected</#if>>
	        			库存：${financialAsset.inventory?string(",##0.00")}元 到期日：${financialAsset.dueDate?string('yyyy-MM-dd')} ${financialAsset.name} 资产金额：${financialAsset.amount?string(",##0.00")}元
	        		</option>
	        	</#list>
	        </select>
	     </div>
	</#if>
</div>
	-->

<div class="form-row">
    <div class="form-label col-md-2">
        <label for="">
            起息日:<span class="required">*</span>
        </label>
    </div>
    <#-->><#if product.id??>
	    <div class="form-label col-md-2">
	        <label>${product.valueDate?string("yyyy-MM-dd HH:mm:ss")}</label>
	    </div>
	    <input type="hidden" id="valueDate" name="valueDate" value="${product.valueDate?string("yyyy-MM-dd HH:mm:ss")}">
	<#else>
	
	-->
		<div class="form-input col-md-2">
		    <#if product.valueDate>
		        <input type="text" id="valueDate" name="valueDate" class="parsley-validated"
		               value="${product.valueDate?string("yyyy-MM-dd HH:mm:ss")}" data-trigger="focus"
		               onClick="WdatePicker({isShowWeek:true,dateFmt:'yyyy-MM-dd HH:mm:ss'})"
		               onchange="checkHolidays();"
		               style="clear:both;overflow:hidden;display:block">
		    <#else>
		        <input type="text" id="valueDate" name="valueDate" class="parsley-validated" value="" data-trigger="focus"
		               onClick="WdatePicker({isShowWeek:true,dateFmt:'yyyy-MM-dd HH:mm:ss'})"
		               onchange="checkHolidays();"
		               style="clear:both;overflow:hidden;display:block">
		    </#if>
	    </div>
	
	<#if product.id?? == false>
	    <div class="form-label col-md-2">
	        <label for="">
	            满标起息
	            <input type="checkbox" checked="checked" name="completedValue" id="nowvalue" value="1" onclick=""/>
	        </label>
	    </div>
	</#if>
</div>
<div class="form-row">
    <div class="form-label col-md-2">
        <label for="">
            起售时间:<span class="required">*</span>
        </label>
    </div>
    <div class="form-input col-md-2">
    <#if product.startTime>
        <input type="text" name="startTime" data-trigger="focus" data-required="true" class="parsley-validated"
               value="${product.startTime?string("yyyy-MM-dd HH:mm:ss")}"
               onClick="WdatePicker({isShowWeek:true,dateFmt:'yyyy-MM-dd HH:mm:ss'})"
               style="clear:both;overflow:hidden;display:block">
    <#else>
        <input type="text" name="startTime" data-trigger="focus" data-required="true" class="parsley-validated" value=""
               onClick="WdatePicker({isShowWeek:true,dateFmt:'yyyy-MM-dd HH:mm:ss'})"
               style="clear:both;overflow:hidden;display:block">
    </#if>
    </div>
    <div class="form-label col-md-2"></div>
    <div class="form-label col-md-2">
        <label for="">
            截止销售时间:<span class="required">*</span>
        </label>
    </div>
    <div class="form-input col-md-2">
    <#if product.endTime>
        <input type="text" id="endTime" name="endTime" data-trigger="focus" data-required="true" class="parsley-validated"
               value="${product.endTime?string("yyyy-MM-dd HH:mm:ss")}"
               onClick="WdatePicker({isShowWeek:true,dateFmt:'yyyy-MM-dd HH:mm:ss'})"
               onchange="checkHolidays();"
               style="clear:both;overflow:hidden;display:block">
    <#else>
        <input type="text" id="endTime" name="endTime" data-trigger="focus" data-required="true" class="parsley-validated" value=""
               onClick="WdatePicker({isShowWeek:true,dateFmt:'yyyy-MM-dd HH:mm:ss'})"
               onchange="checkHolidays();"
               style="clear:both;overflow:hidden;display:block">
    </#if>
    </div>
</div>
<#--收益-->
<div id="earnings-content">
<#if product.id??>
	<#if product.category == 'CURRENT'>
		<div class="form-row">
		    <div class="form-label col-md-2">
		        <label for="">
		            收益规则:
		            <span class="required">*</span>
		        </label>
		    </div>
		    <div class="form-input col-md-8">
		    	<#if product.id??>
		    		<#assign i=0>
		    		<#list product.earningsRules as earningsRule>
		    			<div class="form-row">
		    				<input type="hidden" name="earningsRules[${i}].id" value="${earningsRule.id}">
					        <div class="form-input col-md-1">
						        <a href="javascript:;" class="btn medium primary-bg" title="" onclick="addHoldingTime(this, -1);">
						            <span class="button-content">-</span>
						        </a>
					        </div>
					        <div class="form-input col-md-2">
						        <div class="input-append-wrapper input-append-right">
				                    <div class="input-append bg-gray-alt">天</div>
				                    <div class="append-right">
				                        <input type="text" name="earningsRules[${i}].holdingTime"
				                        	   onchange="checkHoliday( $(this) );"
				                        	   value="${earningsRule.holdingTime}" data-type="number" 
				                        	   data-rangelength="[1,365]" data-trigger="change" 
				                        	   data-required="true" class="parsley-validated">
				                    </div>
				                </div>
					        </div>
					        <div class="form-input col-md-1">
					        	<a href="javascript:;" class="btn medium primary-bg" title="" onclick="addHoldingTime(this, 1);">
						            <span class="button-content">+</span>
						        </a>
					        </div>
					        <div class="form-input col-md-2">
					        	<div class="input-append-wrapper input-append-right">
				                    <div class="input-append bg-gray-alt">%</div>
				                    <div class="append-right">
				                        <input type="text" name="earningsRules[${i}].interestRate" value="${earningsRule.interestRate * 100}"  data-type="number" data-rangelength="[1,100]" data-trigger="change" data-required="true" class="parsley-validated">
				                    </div>
				                </div>
					        </div>
				        </div>
				        <#assign i=i+1>
		    		</#list>
		    		<div class="character-remaining clear input-description font-red">红色天数，为兑付日落到节假日</div>
		    	</#if>
		    </div>
		</div>
	<#else>
		<div class="form-row">
		    <div class="form-label col-md-2">
		        <label for="">
		            期限:
		            <span class="required">*</span>
		        </label>
		    </div>
		    <div class="form-input col-md-2">
		        <input type="text" id="term" name="term" data-type="number" data-trigger="change" data-required="true"
		               class="parsley-validated" value="${product.term}">
		    </div>
		    <div class="col-md-2">天</div>
		    <div class="form-label col-md-2">
		        <label for="">
		            保底期限:
		            <span class="required">*</span>
		        </label>
		    </div>
		    <div class="form-input col-md-2">
		        <input type="text" id="minTerm" name="minTerm" data-type="number" data-trigger="change" data-required="true"
		               class="parsley-validated" value="${product.minTerm}">
		    </div>
		    <div class="col-md-1">天</div>
		  </div>
		  <div class="form-row">
		    <div class="form-label col-md-2">
		        <label for="">
		            年化:<span class="required">*</span>
		        </label>
		    </div>
		    <div class="form-input col-md-2">
		        <input type="hidden" id="interestRate" name="interestRate" data-type="number" data-rangelength="[1,5]"
		               data-trigger="change" data-required="true" class="parsley-validated" value="${product.interestRate}">
		    <#if product>
		        <input type="text" id="interestRateDisplay" data-type="number" data-rangelength="[1,5]" data-trigger="change"
		               data-required="true" class="parsley-validated" value="${product.interestRate?number*100}">
		    <#else>
		        <input type="text" id="interestRateDisplay" data-type="number" data-rangelength="[1,5]" data-trigger="change"
		               data-required="true" class="parsley-validated" value="">
		    </#if>
		    </div>
		    <div class="col-md-2">%</div>
		</div>
	</#if>
<#else>
<div class="form-row">
    <div class="form-label col-md-2">
        <label for="">
            期限:
            <span class="required">*</span>
        </label>
    </div>
    <div class="form-input col-md-2">
        <input type="text" id="term" name="term" data-type="number" data-trigger="change" data-required="true"
               class="parsley-validated" value="${product.term}">
    </div>
    <div class="col-md-2">天</div>
    <div class="form-label col-md-2">
        <label for="">
            保底期限:
            <span class="required">*</span>
        </label>
    </div>
    <div class="form-input col-md-2">
        <input type="text" id="minTerm" name="minTerm" data-type="number" data-trigger="change" data-required="true"
               class="parsley-validated" value="${product.minTerm}">
    </div>
    <div class="col-md-2">天</div>
</div>
<div class="form-row">
    <div class="form-label col-md-2">
        <label for="">
            年化:<span class="required">*</span>
        </label>
    </div>
    <div class="form-input col-md-2">
        <input type="hidden" id="interestRate" name="interestRate" data-type="number" data-rangelength="[1,5]"
               data-trigger="change" data-required="true" class="parsley-validated" value="${product.interestRate}">
    <#if product>
        <input type="text" id="interestRateDisplay" data-type="number" data-rangelength="[1,5]" data-trigger="change"
               data-required="true" class="parsley-validated" value="${product.interestRate?number*100}">
    <#else>
        <input type="text" id="interestRateDisplay" data-type="number" data-rangelength="[1,5]" data-trigger="change"
               data-required="true" class="parsley-validated" value="">
    </#if>
    </div>
    <div class="col-md-2">%</div>
</div>
</#if>
</div>
<div class="form-row">
    <div class="form-label col-md-2">
        <label for="">
            平台奖励:
        </label>
    </div>
    <div class="form-input col-md-2">
        <input type="hidden" id="bonusRate" name="bonusRate" data-type="number" class="parsley-validated"
               data-rangelength="[1,5]" value="${product.bonusRate}">
    <#if product>
        <input type="text" id="bonusRateDisplay" name="bonusRate" data-type="number" class="parsley-validated"
               data-rangelength="[1,5]" value="${product.bonusRate?number*100}">
    <#else>
        <input type="text" id="bonusRateDisplay" name="bonusRate" data-type="number" class="parsley-validated"
               data-rangelength="[1,5]" value="">
    </#if>
    </div>
    <div class="col-md-2">%</div>
</div>
<div class="form-row">
    <div class="form-label col-md-2">
        <label for="">
            总金额:<span class="required">*</span>
        </label>
    </div>
    <#if product.id??>
	    <div class="form-label col-md-4">
	        <label>${product.totalAmount}元</label>
	    </div>
	<#else>
	    <div class="form-input col-md-2">
	        <input type="text" id="totalAmount" name="totalAmount" data-type="number" data-trigger="change"
	               data-required="true" class="parsley-validated" value="${product.totalAmount}">
	    </div>
	    <div class="col-md-2">元</div>
	</#if>
    <div class="form-label col-md-2">
        <label for="">
            显示总金额:
        </label>
    </div>
    <div class="form-input col-md-2">
        <input type="text" id="displayTotalAmount" name="displayTotalAmount" data-type="number" data-trigger="change"
               class="parsley-validated" value="${product.displayTotalAmount}">
    </div>
    <div class="col-md-2">元</div>
</div>
<div class="form-row">
    <div class="form-label col-md-2">
        <label for="">
            起售金额:<span class="required">*</span>
        </label>
    </div>
    <div class="form-input col-md-2">
        <input type="text" id="minAmount" name="minAmount" data-type="number" data-trigger="change" data-required="true"
               class="parsley-validated" value="${product.minAmount}">
    </div>
    <div class="col-md-2">元</div>
    <div class="form-label col-md-2">
        <label for="">
            限购金额:
        </label>
    </div>
    <div class="form-input col-md-2">
        <input type="text" id="maxAmount" name="maxAmount" data-type="number" data-trigger="change"
               class="parsley-validated" value="${product.maxAmount}">
    </div>
    <div class="col-md-2">元</div>
</div>
<div class="form-row">
    <div class="form-label col-md-2">
        <label for="">
            风险等级:<span class="required">*</span>
        </label>
    </div>
    <div class="form-input col-md-2">
        <select name="riskLevel">
            <option value="R1" <#if product.riskLevel == 'R1'>selected</#if>>R1</option>
            <option value="R2" <#if product.riskLevel == 'R2'>selected</#if>>R2</option>
            <option value="R3" <#if product.riskLevel == 'R3'>selected</#if>>R3</option>
        </select>
    </div>
    <div class="form-label col-md-2"></div>
</div>

<div class="form-row">
    <div class="form-label col-md-2">
        <label for="">
            备注:
        </label>
    </div>
    <div class="form-input col-md-8">
        <input type="text" id="remark" name="remark" data-trigger="change" class="parsley-validated"
               value="${product.remark}">
    </div>
</div>
<div class="form-row">
		<div class="form-label col-md-2">
        <label for="">
            企业码:
        </label>
	    </div>
	    <div class="form-input col-md-2">
	        <input type="text" id="enterpriseCode" name="enterpriseCode" data-trigger="change" class="parsley-validated"
	               value="${product.enterpriseCode}">
	    </div>
	    <div class="form-label col-md-2"></div>
	    <div class="form-label col-md-2">
        <label for="">
            发布渠道:
        </label>
	    </div>
	    <div class="form-input col-md-2">
	        <input type="text" id="channel" name="channel" data-trigger="change" class="parsley-validated"
	               value="${product.channel}">
	    </div>
</div>
<div class="form-row">
    <div class="form-label col-md-2">
        <label for="">
            模板类别:
        </label>
    </div>
    <div class="form-input col-md-2">
        <select id="typeSelect" name="typeId">
            <option value="">无分类</option>
        <#list productTypeList as type>
            <#if type.id == product.type.id>
                <option value="${type.id}" selected="selected">${type.name}</option>
            <#else>
                <option value="${type.id}">${type.name}</option>
            </#if>
        </#list>
        </select>
    </div>
</div>

<#--自定义模板-->
<input type="hidden" id="productTypeFields" name="productTypeFields"/>
<input type="hidden" id="ctxTemplateValue" name="ctxTemplateValue"/>
<input type="hidden" id="appTemplateValue" name="appTemplateValue"/>
<input type="hidden" id="protocolsTemplateValue" name="protocolsTemplateValue"/>

<div id="templateDiv">
<#if productTypeFieldValue>
    <div id="productTypeFieldsValue" class="form-row">
        <#list productTypeFields as field>
        <div class="col-md-6">
        	<div class=" form-row">
            <div class="form-label col-md-4">
                <label for="">
                ${field.name}
                </label>
            </div>
            <div class="form-input col-md-${field.css}">
                <#if field.type == "文字">
                    <input type="text" <#if field.required == "REQUIRED">data-required="true"</#if> name="field_${field.code}"
                           value="${productTypeFieldValue[field.code]!""}"
                           data-code="'+element.code+'" data-trigger="change" class="parsley-validated"/>
                <#elseif field.type == "图片">
                    <input id="text" <#if field.required == "REQUIRED">data-required="true"</#if>  type="text" name="field_${field.code}"
                           value="${productTypeFieldValue[field.code]!""}"
                           data-trigger="change" class="parsley-validated" />
                <#else>
                    <input type="text" <#if field.required == "REQUIRED">data-required="true"</#if>  name="field_${field.code}"
                           value="${productTypeFieldValue[field.code]!""}"
                           data-trigger="change" dataRequired class="parsley-validated" />
                </#if>

            </div>
            <#if field.type == "图片">
                <div class="form-label col-md-2">
                    <a class="btn medium primary-bg radius-all-4" onclick="uploadDialog(this)">
                        <span class="button-content">上传图片</span>
                    </a>
                </div>
            </#if>
            </div>
            </div>
        </#list>
    </div>
</#if>
</div>
<div id="descriptionDiv" class="form-row">
    <div class="form-label col-md-2">
        <label for="">
            描述:<span class="required">*</span>
        </label>
    </div>
    <div class="content-box bg-white post-box col-md-8">
        <input type="hidden" name="description" value='' id="conhtml"/>
        <script id="editor" type="text/plain" style="width:100%;height:500px;">${product.description}</script>
    </div>
</div>
<div id="appDescriptionDiv" class="form-row">
    <div class="form-label col-md-2">
        <label for="">
            app描述:<span class="required">*</span>
        </label>
    </div>
    <div class="content-box bg-white post-box col-md-8">
        <input type="hidden" name="appDescription" value='' id="conhtml2"/>
        <script id="editor2" type="text/plain" style="width:100%;height:500px;">${product.appDescription}</script>
    </div>
</div>
<div id="insuranceDiv" class="form-row">
    <div class="form-label col-md-2">
        <label for="">
            安全保障:<span class="required">*</span>
        </label>
    </div>
    <div class="content-box bg-white post-box col-md-8">
        <input type="hidden" name="insurance" value='' id="conhtml3"/>
        <script id="editor3" type="text/plain" style="width:100%;height:500px;">${product.insurance}</script>
    </div>
</div>
<div class="form-row">
    <div class="form-label col-md-2">
        <label for="">
            排序:
        </label>
    </div>
    <div class="form-input col-md-2">
        <input type="text" id="sequnce" name="sequnce" data-trigger="change" class="parsley-validated"
               value="${product.sequnce}">值越大越优先
    </div>
</div>
<div class="form-row">
    <div class="form-label col-md-2">
        <label for="">
            活动:
        </label>
    </div>
    <div class="form-input col-md-4">
        <select id="activitySelect" name="activitys" multiple="" class="chosen-select">
        <#list saleActivityList as activity>
            <option value="${activity.id}" <#list product.activitys?split(",") as aid><#if aid==activity.id>selected</#if></#list>>${activity.name}</option>
        </#list>
        </select>
    </div>
</div>
<div id="productDiv" class="form-row">
    <div class="form-label col-md-2">
        <label for="">
            协议:
        </label>
    </div>
    <div class="form-label col-md-2">
        <a href="javascript:;" class="bg-gray-alt medium radius-all-2 display-block btn basic-dialog"
           onclick="showAddProtocal();">
            <span class="button-content text-center float-none font-size-9">添加</span>
        </a>
    </div>
</div>

<div class="form-row">
        <div class="form-label col-md-2">
            <label for="">
                是否新手标:
                <span class="required">*</span>
            </label>
        </div>
        <div class="form-input col-md-2">
            <select name="rookie">
            	<option value="0" <#if !product.rookie>selected</#if>>否</option>
        		<option value="1" <#if product.rookie>selected</#if>>是</option>
        	</select>
        </div>
    </div>

<div class="form-row">
    <div class="form-label col-md-2">
    </div>
    <div id="protocol-rows" class="form-label col-md-10">
        <div id="protocol-row-template" class="hide" style="margin:8px 0">
            <input type="hidden" name="protocolIds">
            <span class="btn large font-size-15 bg-gray-alt"><a href="javascript:;"></a></span>
            <a href="javascript:;" class="btn btn-post large bg-red font-size-15" style="width:60px">删除</a>
        </div>
    </div>
</div>

</form>
<div class="divider"></div>
<div class="form-row">
    <input type="hidden" name="superhidden" id="superhidden">

    <div class="form-input col-md-10 col-md-offset-2">
        <a href="javascript:;" class="btn medium primary-bg radius-all-4 col-md-2" id="demo-form-2-valid">
            提交
        </a>
    </div>
</div>
</div>
</div>

<div class="hide" id="add-protocal-template">
    <div class="pad10A">
        <form>
            <div class="form-row">
                <div class="form-input col-md-12">
                    <input type="text" id="editor-title" placeholder="协议标题" name="title" data-trigger="change"
                           data-required="true" class="parsley-validated"/>
                </div>
            </div>
            <div class="form-row">
                <div class="form-input col-md-12">
                    <input type="hidden" name="content" value='' id="content"/>
                    <script id="editor-content" type="text/plain" style="width:675px;height:300px;"></script>
                </div>
            </div>
        </form>
    </div>
</div>


<div class="hide" id="update-protocal-template">
    <div class="pad10A">
        <form>
            <div class="form-row">
                <div class="form-input col-md-12">
                    <input type="text" id="updatetitle" placeholder="协议标题" name="title" data-trigger="change"
                           data-required="true" class="parsley-validated"/>
                </div>
            </div>
            <div class="form-row">
                <div class="form-input col-md-12">
                    <input type="hidden" name="content" value='' id="content"/>
                    <script id="updatecontent" type="text/plain" style="width:675px;height:300px;"></script>
                </div>
            </div>
        </form>
    </div>
</div>

<#--固定利率收益模板-->
<div class="hide" id="fixed-interest-rate-template">
<div class="form-row">
    <div class="form-label col-md-2">
        <label for="">
            期限:
            <span class="required">*</span>
        </label>
    </div>
    <div class="form-input col-md-2">
        <input type="text" id="term" name="term" data-type="number" data-trigger="change" data-required="true"
               class="parsley-validated" value="">
    </div>
    <div class="col-md-2">天</div>
 
 	<div class="form-label col-md-2">
        <label for="">
            保底期限:
            <span class="required">*</span>
        </label>
    </div>
    <div class="form-input col-md-2">
        <input type="text" id="minTerm" name="minTerm" data-type="number" data-trigger="change" data-required="true"
               class="parsley-validated" value="">
    </div>
    <div class="col-md-2">天</div>
 
 </div>
 <div class="form-row">
    <div class="form-label col-md-2">
        <label for="">
            年化:<span class="required">*</span>
        </label>
    </div>
    <div class="form-input col-md-2">
        <input type="hidden" id="interestRate" name="interestRate" data-type="number" data-rangelength="[1,5]"
               data-trigger="change" data-required="true" class="parsley-validated" value="">
    <#if product>
        <input type="text" id="interestRateDisplay" data-type="number" data-rangelength="[1,5]" data-trigger="change"
               data-required="true" class="parsley-validated" value="">
    <#else>
        <input type="text" id="interestRateDisplay" data-type="number" data-rangelength="[1,5]" data-trigger="change"
               data-required="true" class="parsley-validated" value="">
    </#if>
    </div>
    <div class="col-md-2">%</div>
</div>
</div>

<#--收益规则模板-->
<div class="hide" id="earnings-rule-template">
<div class="form-row">
    <div class="form-label col-md-2">
        <label for="">
            收益规则:
            <span class="required">*</span>
        </label>
    </div>
    <div class="form-input col-md-8">
    	<div class="form-row">
	        <div class="form-input col-md-1">
		        <a href="javascript:;" class="btn medium primary-bg" title="" onclick="addHoldingTime(this, -1);">
		            <span class="button-content">-</span>
		        </a>
	        </div>
	        <div class="form-input col-md-2">
		        <div class="input-append-wrapper input-append-right">
	                <div class="input-append bg-gray-alt">天</div>
	                <div class="append-right">
	                    <input type="text" name="earningsRules[0].holdingTime" 
	                    onchange="checkHoliday( $(this) );"
	                    value="30" data-type="number" data-rangelength="[1,365]" data-trigger="change" data-required="true" class="parsley-validated">
	                </div>
	            </div>
	        </div>
	        <div class="form-input col-md-1">
	        	<a href="javascript:;" class="btn medium primary-bg" title="" onclick="addHoldingTime(this, 1);">
		            <span class="button-content">+</span>
		        </a>
	        </div>
	        <div class="form-input col-md-2">
	        	<div class="input-append-wrapper input-append-right">
	                <div class="input-append bg-gray-alt">%</div>
	                <div class="append-right">
	                    <input type="text" name="earningsRules[0].interestRate" value=""  data-type="number" data-rangelength="[1,100]" data-trigger="change" data-required="true" class="parsley-validated">
	                </div>
	            </div>
	        </div>
	    </div>
	    <div class="form-row">
	        <div class="form-input col-md-1">
		        <a href="javascript:;" class="btn medium primary-bg" title="" onclick="addHoldingTime(this, -1);">
		            <span class="button-content">-</span>
		        </a>
	        </div>
	        <div class="form-input col-md-2">
		        <div class="input-append-wrapper input-append-right">
	                <div class="input-append bg-gray-alt">天</div>
	                <div class="append-right">
	                    <input type="text" name="earningsRules[1].holdingTime" 
	                    onchange="checkHoliday( $(this) );"
	                    value="60" data-type="number" data-rangelength="[1,365]" data-trigger="change" data-required="true" class="parsley-validated">
	                </div>
	            </div>
	        </div>
	        <div class="form-input col-md-1">
	        	<a href="javascript:;" class="btn medium primary-bg" title="" onclick="addHoldingTime(this, 1);">
		            <span class="button-content">+</span>
		        </a>
	        </div>
	        <div class="form-input col-md-2">
	        	<div class="input-append-wrapper input-append-right">
	                <div class="input-append bg-gray-alt">%</div>
	                <div class="append-right">
	                    <input type="text" name="earningsRules[1].interestRate" value=""  data-type="number" data-rangelength="[1,100]" data-trigger="change" data-required="true" class="parsley-validated">
	                </div>
	            </div>
	        </div>
	    </div>
	    <div class="form-row">
	        <div class="form-input col-md-1">
		        <a href="javascript:;" class="btn medium primary-bg" title="" onclick="addHoldingTime(this, -1);">
		            <span class="button-content">-</span>
		        </a>
	        </div>
	        <div class="form-input col-md-2">
		        <div class="input-append-wrapper input-append-right">
	                <div class="input-append bg-gray-alt">天</div>
	                <div class="append-right">
	                    <input type="text" name="earningsRules[2].holdingTime" 
	                    onchange="checkHoliday( $(this) );"
	                    value="90" data-type="number" data-rangelength="[1,365]" data-trigger="change" data-required="true" class="parsley-validated">
	                </div>
	            </div>
	        </div>
	        <div class="form-input col-md-1">
	        	<a href="javascript:;" class="btn medium primary-bg" title="" onclick="addHoldingTime(this, 1);">
		            <span class="button-content">+</span>
		        </a>
	        </div>
	        <div class="form-input col-md-2">
	        	<div class="input-append-wrapper input-append-right">
	                <div class="input-append bg-gray-alt">%</div>
	                <div class="append-right">
	                    <input type="text" name="earningsRules[2].interestRate" value=""  data-type="number" data-rangelength="[1,100]" data-trigger="change" data-required="true" class="parsley-validated">
	                </div>
	            </div>
	        </div>
	    </div><div class="form-row">
	        <div class="form-input col-md-1">
		        <a href="javascript:;" class="btn medium primary-bg" title="" onclick="addHoldingTime(this, -1);">
		            <span class="button-content">-</span>
		        </a>
	        </div>
	        <div class="form-input col-md-2">
		        <div class="input-append-wrapper input-append-right">
	                <div class="input-append bg-gray-alt">天</div>
	                <div class="append-right">
	                    <input type="text" name="earningsRules[3].holdingTime" 
	                    onchange="checkHoliday( $(this) );"
	                    value="120" data-type="number" data-rangelength="[1,365]" data-trigger="change" data-required="true" class="parsley-validated">
	                </div>
	            </div>
	        </div>
	        <div class="form-input col-md-1">
	        	<a href="javascript:;" class="btn medium primary-bg" title="" onclick="addHoldingTime(this, 1);">
		            <span class="button-content">+</span>
		        </a>
	        </div>
	        <div class="form-input col-md-2">
	        	<div class="input-append-wrapper input-append-right">
	                <div class="input-append bg-gray-alt">%</div>
	                <div class="append-right">
	                    <input type="text" name="earningsRules[3].interestRate" value=""  data-type="number" data-rangelength="[1,100]" data-trigger="change" data-required="true" class="parsley-validated">
	                </div>
	            </div>
	        </div>
	    </div><div class="form-row">
	        <div class="form-input col-md-1">
		        <a href="javascript:;" class="btn medium primary-bg" title="" onclick="addHoldingTime(this, -1);">
		            <span class="button-content">-</span>
		        </a>
	        </div>
	        <div class="form-input col-md-2">
		        <div class="input-append-wrapper input-append-right">
	                <div class="input-append bg-gray-alt">天</div>
	                <div class="append-right">
	                    <input type="text" name="earningsRules[4].holdingTime" 
	                    onchange="checkHoliday( $(this) );"
	                    value="150" data-type="number" data-rangelength="[1,365]" data-trigger="change" data-required="true" class="parsley-validated">
	                </div>
	            </div>
	        </div>
	        <div class="form-input col-md-1">
	        	<a href="javascript:;" class="btn medium primary-bg" title="" onclick="addHoldingTime(this, 1);">
		            <span class="button-content">+</span>
		        </a>
	        </div>
	        <div class="form-input col-md-2">
	        	<div class="input-append-wrapper input-append-right">
	                <div class="input-append bg-gray-alt">%</div>
	                <div class="append-right">
	                    <input type="text" name="earningsRules[4].interestRate" value=""  data-type="number" data-rangelength="[1,100]" data-trigger="change" data-required="true" class="parsley-validated">
	                </div>
	            </div>
	        </div>
	    </div><div class="form-row">
	        <div class="form-input col-md-1">
		        <a href="javascript:;" class="btn medium primary-bg" title="" onclick="addHoldingTime(this, -1);">
		            <span class="button-content">-</span>
		        </a>
	        </div>
	        <div class="form-input col-md-2">
		        <div class="input-append-wrapper input-append-right">
	                <div class="input-append bg-gray-alt">天</div>
	                <div class="append-right">
	                    <input type="text" name="earningsRules[5].holdingTime" 
	                    onchange="checkHoliday( $(this) );"
	                    value="180" data-type="number" data-rangelength="[1,365]" data-trigger="change" data-required="true" class="parsley-validated">
	                </div>
	            </div>
	        </div>
	        <div class="form-input col-md-1">
	        	<a href="javascript:;" class="btn medium primary-bg" title="" onclick="addHoldingTime(this, 1);">
		            <span class="button-content">+</span>
		        </a>
	        </div>
	        <div class="form-input col-md-2">
	        	<div class="input-append-wrapper input-append-right">
	                <div class="input-append bg-gray-alt">%</div>
	                <div class="append-right">
	                    <input type="text" name="earningsRules[5].interestRate" value=""  data-type="number" data-rangelength="[1,100]" data-trigger="change" data-required="true" class="parsley-validated">
	                </div>
	            </div>
	        </div>
	    </div>
	    <div class="character-remaining clear input-description font-red">红色天数，为兑付日落到节假日</div>
    </div>
</div>
</div>

<script>
var uploadUrl;
var uploadText;

<#if product!=null>
var uySaveFloder = "product/${product.id}";
</#if>
<#if product==null>
var uySaveFloder = "product/" + new Date().getFullYear() + "" + new Date().getMonth() + "" + new Date().getDate();
</#if>

function getObjectURL(file) {
    var url = null ;
    if (window.createObjectURL!=undefined) { // basic
        url = window.createObjectURL(file) ;
    } else if (window.URL!=undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file) ;
    } else if (window.webkitURL!=undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file) ;
    }
    return url ;
}

//实现预览功能
function preview(a) {
    var objUrl = getObjectURL(a.files[0]) ;
    console.log("objUrl = "+objUrl) ;
    if (objUrl) {
        // attr("src", objUrl);'<img width="120" height="120" style="display: inherit;" src="'+objUrl+'" />'
        console.log($("#ImgPr"));
        $("#ImgPr").attr("src", objUrl);
    }
    return;
}

$(function () {


<#if product.type>
    $("#descriptionDiv").hide();
    $("#appDescriptionDiv").hide();
    $("#appDescriptionDiv").hide();
    $("#insuranceDiv").hide();
    $("#productDiv").hide();
</#if>

    //ajax更新拓展字段
    $('#typeSelect').change(function () {
        var typeId = $(this).children('option:selected').val();//这就是selected的值
        //$("#typeId").val(typeId);
        if (typeId == "") {
            $("#templateDiv").empty();
            $("#descriptionDiv").show();
            $("#appDescriptionDiv").show();
            $("#insuranceDiv").show();
            $("#productDiv").show();
            return;
        }
        $("#descriptionDiv").hide();
        $("#appDescriptionDiv").hide();
        $("#insuranceDiv").hide();
        $("#productDiv").hide();
        $.post("/products/productType/fields", {typeId: typeId}, function (data) {

            $("#templateDiv").empty();

            //加载内容自定义字段
            if (data.productTypeFields) {
                var html = '<div id="productTypeFieldsValue" class="form-row">';
                for (var i = 0; i < data.productTypeFields.length; i++) {
                    var dataRequired = '';
                    var input = '';
                    var fileDiv = '';
                    if (data.productTypeFields[i].required == "REQUIRED") {
                        dataRequired = 'data-required="true"';
                    }
                    if (data.productTypeFields[i].type == "文字") {
                        input = '<input type="text" name="field_' + data.productTypeFields[i].code + '" data-trigger="change"' +
                                dataRequired + '  class="parsley-validated" />';
                    }
                    if (data.productTypeFields[i].type == "图片") {
                        input = '<input id="text"  type="text" name="field_' + data.productTypeFields[i].code + '" data-trigger="change"' +
                                dataRequired + '  class="parsley-validated" />';

                        fileDiv = '<div class="form-label col-md-2">'+
                                '<a class="btn medium primary-bg radius-all-4" onclick="uploadDialog(this)">'+
                                '<span class="button-content">上传图片</span>'+
                                '</a>'+
                                '</div>';
                    }
                    if (data.productTypeFields[i].type == "数值") {
                        input = '<input type="text" name="field_' + data.productTypeFields[i].code + '" data-trigger="change"' +
                                dataRequired + '  class="parsley-validated" />';
                    }

                    html += '<div class="col-md-6"><div class=" form-row"><div class="form-label col-md-4">' +
                            '<label for="">' +
                            data.productTypeFields[i].name +
                            '</label>' +

                            '</div>' +
                            '<div class="form-input col-md-' + data.productTypeFields[i].css + '">' +
                            input +
                            '</div>' +
                            fileDiv + '</div></div>';

                }
                html += '</div>';
                $("#templateDiv").append(html);
            }
        });
    });

    var ue = UE.getEditor('editor', {upYunSaveFolder: uySaveFloder});
    ue.options.allowDivTransToP = false;

    var ue2 = UE.getEditor('editor2', {upYunSaveFolder: uySaveFloder});
    ue2.options.allowDivTransToP = false;

    var ue3 = UE.getEditor('editor3', {upYunSaveFolder: uySaveFloder});
    ue3.options.allowDivTransToP = false;

    var ue4 = UE.getEditor('editor-content', {upYunSaveFolder: uySaveFloder});
    ue4.options.allowDivTransToP = false;

    var ue5 = UE.getEditor('updatecontent', {upYunSaveFolder: uySaveFloder});
    ue5.options.allowDivTransToP = false;

    function getTV(eleID) {
        var eles = $("#" + eleID + " input[type!=file]");
        var value = "{";
        for (var i = 0; eles != null && i < eles.length; i++) {
            if (i > 0) {
                value += ',';
            }
            value += '"' + eles[i].name.substring(6) + '":"' + eles[i].value + '"';
        }
        value += "}";
        return value;
    }

    $("#demo-form-2-valid").click(function () {
        //年化收益保存时需缩小100倍
        $('#interestRate').val($('#interestRateDisplay').val() / 100);
        $('#bonusRate').val($('#bonusRateDisplay').val() / 100);
        $('#demo-form1').parsley('validate');
        $("#conhtml").val(UE.getEditor('editor').getContent());
        $("#conhtml2").val(UE.getEditor('editor2').getContent());
        $("#conhtml3").val(UE.getEditor('editor3').getContent());

        if ($("#conhtml").val() == "") {
            //   alert("描述不为空");
            //	return false;
        }

        //产品类别自定义属性值
        $("#productTypeFields").val(getTV("productTypeFieldsValue"));

        //protocols
        var protocols = $("#protocols");
        if (protocols.length > 0) {
            var id = protocols.val().split(",");
            var pv = "";
            for (var j = 0; j < id.length; j++) {
                if (j > 0) {
                    pv += "||";
                }
                pv += getTV("protocol_" + id[j] + "Template");
            }
            $("#protocolsTemplateValue").val(pv);
        }

		// 兑付日是否落在节假日
		if($('#category').val() == 'CURRENT'){
			var holdingTimes = $('#earnings-content input[name$="holdingTime"][class*="font-red"]');
			if(holdingTimes.length > 0){
				$.messager.confirm("提示", "结息日是节假日，确定发布产品？", function () {
					$('#demo-form1').trigger('submit');
				});
			}else{
				$('#demo-form1').trigger('submit');
			}
		}else{
			var data = {"valueDate":$("#valueDate").val(),"endTime":$("#endTime").val(),"term":$("#term").val()};
	        $.ajax(
				{url:"/products/isHoliday",
				data:data,
				type:'post',
				dataType:'json',
				success:function(data){
					if(data['status']==0){
						$('#demo-form1').trigger('submit');
					}else{
						$.messager.confirm("提示", "结息日是节假日，确定发布产品？", function () {
							$('#demo-form1').trigger('submit');
						});
					}
				}}
			);
		}
    });
    var template = $('#protocol-row-template');
<#list protocol as being>

    var row = template.clone();

    row.removeAttr('id');
    row.removeAttr('class');

    row.attr('id',${being.id});
    row.find('input').val(${being.id});
    row.find('span a').html('${being.title}');
    row.find('a').attr('onclick', 'deleteProtocol("' + ${being.id} +'");');
    row.find('span a').attr('onclick', 'updateProtocol("' + ${being.id} +'");');
    template.after(row);
</#list>

})
var cbox = $('#nowvalue');
var cput = $('#valueDate');
cbox.click(function () {
    if (cbox.prop('checked')) {
        cput.val("");
        cput.attr('disabled', true);
    } else {
        cput.attr('disabled', false);
    }

});


function showAddProtocal() {


    var template = $('#add-protocal-template');
    var html = '<div id="dialog" title="添加协议"><div>' + template.html() + '</div></div>';

    $(html).dialog({
        minWidth: 700,
        minHeight: 350,
        model: !0,
        dialogClass: "modal-dialog",
        closeOnEscape: !0,
        close: function () {
            $(this).dialog('destroy');
        },
        buttons: {
            提交: function () {
                var valid = $('#dialog form').parsley('validate');
                if (!valid) {
                    return valid;
                }
                $("#dialog #content").val(UE.getEditor('editor-content').getContent());

                $.post("/protocols", $('#dialog form').serialize())
                        .done(function (data) {
                            if (data.status == 'success') {
                                $.jGrowl(data.message, {sticky: !1, position: 'top-right', theme: 'bg-green'});

                                var template = $('#protocol-row-template');

                                var row = template.clone();
                                row.removeAttr('id');
                                row.removeAttr('class');

                                row.attr('id', data.data.id);
                                row.find('input').val(data.data.id);
                                row.find('span a').html(data.data.title);

                                row.find('a').attr('onclick', 'deleteProtocol("' + data.data.id + '");');
                                row.find('span a').attr('onclick', 'updateProtocol("' + data.data.id + '");');
                                template.after(row);
                            }
                        })
                        .fail(function () {
                            $.jGrowl('添加协议失败', {sticky: !1, position: 'top-right', theme: 'bg-red'});
                        });

                $('#dialog').dialog('close');
            }
        }
    });
}
;

function deleteProtocol(id) {
    $.messager.confirm("提示", "确认删除协议吗？", function () {

        $.post('/protocols/delete/' + id)
                .done(function (data) {
                    if (data.status == 'success') {
                        $.jGrowl(data.message, {sticky: !1, position: 'top-right', theme: 'bg-green'});

                        $('#protocol-rows').find('div[id=' + data.data + ']').remove();
                    }
                })
                .fail(function () {
                    $.jGrowl('删除协议失败', {sticky: !1, position: 'top-right', theme: 'bg-red'});
                });
    });
}

var gContent;
function updateProtocol(id) {
    $.post('/protocols/showupdate/' + id)
            .done(function (data) {
                if (data.status == 'success') {
                    var template = $('#update-protocal-template');
                    var html = '<div id="dialog" title="修改协议"><div>' + template.html() + '</div></div>';
                    $(html).dialog({
                        minWidth: 700,
                        minHeight: 350,
                        model: !0,
                        dialogClass: "modal-dialog",
                        closeOnEscape: !0,
                        close: function () {
                            $(this).dialog('destroy');
                        },
                        buttons: {
                            提交: function () {
                                var valid = $('#dialog form').parsley('validate');
                                if (!valid) {
                                    return valid;
                                }
                                $("#dialog #content").val(UE.getEditor('updatecontent').getContent());

                                $.post('/protocols/update/' + id, $('#dialog form').serialize())
                                        .done(function (data) {
                                            if (data.status == 'success') {

                                                $.jGrowl(data.message, {sticky: !1, position: 'top-right', theme: 'bg-green'});
                                                $('#' + data.data.id).find('span a').html(data.data.title);

                                            }
                                        })
                                        .fail(function () {
                                            $.jGrowl('修改协议失败', {sticky: !1, position: 'top-right', theme: 'bg-red'});
                                        });

                                $('#dialog').dialog('close');
                            }
                        }
                    });
                    gContent = data.data.content;
                    var fn = function () {
                        UE.getEditor('updatecontent').setContent(gContent);
                    }
                    UE.getEditor('updatecontent').addListener("ready", fn);
                    $('#dialog #updatetitle').attr('value', data.data.title);

                }
            })
            .fail(function () {
                $.jGrowl('修改协议失败', {sticky: !1, position: 'top-right', theme: 'bg-red'});
            });

}

//上传图片对话框
function uploadDialog(a){
    uploadText = $(a).parent().prev().children("#text")[0];

    var html =
            '<div id="dialog" class="hide" title="图片上传">' +
                '<div id="uploadImageDialog">'+
                    '<div  style=" width:120px; height:120px;margin:auto">'+
                    '<img id="ImgPr" width="120" height="120" style="display: inherit;" />'+
                    '</div>'+
                    '<input id="fileupload" type="file" multiple style="margin-left:100px;margin-top:20px" onchange="preview(this)"/>'+
                    '<div style="margin-top: 20px;margin-left: 100px">'+
                    '地址：<a id="uploadAddress"></a>'+
                    '</div >'+
                    '<div style="width:60px;  margin:auto; margin-top:20px">'+
                    '<a class="btn medium primary-bg radius-all-4" onclick="uploadImage(this)">'+
                        '<span class="button-content">上传</span>'+
                    '</a>'+
                    '</div>'+
                '</div>'+
            '</div>';
    $( html ).dialog({
        resizable:!0,
        minWidth:700,
        minHeight:350,
        modal:!0,
        dialogClass:"modal-dialog",
        closeOnEscape:!0,
        close : function() {
            $( this ).dialog( "destroy" );
        },
        buttons: {
            确定: function() {
                $( this ).dialog( "destroy" );
            }
        }
    });
}

//上传图片
function uploadImage(a) {

    $.get("/upyun/bucketapi", function (data) {

        var config = {
            api: 'http://v0.api.upyun.com/',
            bucket: data.bucket,

            // 空间的表单 API
            form_api: data.formId
        };

        var inputtext = $(a).parent().prev().children("#text")[0];
        var inputfile = $(a).parent().children("#file")[0];

        var file = $("#fileupload")[0].files[0];


        if (!file) {
            console.log('no file is selected');
            return;
        }
        var dir = "upload/images/";
        // 计算 policy 和 signature 所需的参数
        // 详情见： http://docs.upyun.com/api/form_api/#表单API接口简介
        var options = {
            bucket: config.bucket,
            expiration: Math.floor(new Date().getTime() / 1000) + 86400,
            'save-key': dir+file.name
        };


        var policy = window.btoa(JSON.stringify(options));
        var signature = CryptoJS.MD5(policy + '&' + config.form_api);

        var dataform = new FormData();
        dataform.append('policy', policy);
        dataform.append('signature', signature);
        dataform.append('file', file);

        var request = new XMLHttpRequest();
        request.open('POST', config.api + options.bucket);

        request.onload = function (e) {
//            console.log(request.response);
//            alert(request.response);
            var jsonResponse = JSON.parse(request.response);
            if (jsonResponse.code == "200") {
                uploadUrl = data.returnUrl + '/'+dir + file.name;

                $(inputtext).val(data.returnUrl + '/'+dir + file.name);
                $(uploadText).val(uploadUrl);

                $("#uploadAddress").attr("href", data.returnUrl + '/'+dir + file.name);
                $("#uploadAddress").text(uploadUrl);

                uploadUrl = "";
                uploadText = "";
                $.jGrowl("上传成功", {sticky: !1, position: "top-right", theme: "bg-green"});

            } else {
                uploadUrl = "";
                uploadText = "";
                $.jGrowl("上传失败，错误代码"+jsonResponse.code, {sticky: !1, position: "top-right", theme: "bg-green"});
            }
        };

        request.send(dataform);

    });
}

// 产品类别改变处理
function onCategoryChanged() {
	var category = $('#category').val();
	if(category == 'CURRENT'){
		$('#earnings-content').html($('#earnings-rule-template').html());
		checkHolidays();
	}else{
		$('#earnings-content').html($('#fixed-interest-rate-template').html());
	}
}

// 检查节假日
function checkHolidays(){

	if($("#valueDate").val() == '' && $("#endTime").val() == ''){
		return;
	}
	
	var valueDate = $('#valueDate').val();
	var holdingTimes = $('#earnings-content input[name$="holdingTime"]');
	for(var i = 0; i < holdingTimes.length; i++){
		var holdingTime = Number($(holdingTimes[i]).val());
		checkHoliday( $(holdingTimes[i]) );
	}
}

// 检查节假日
// holdingTime 持有时间
function checkHoliday( holdingTime ){
	if(holdingTime.val() == ''){
		return;
	}
	
	if($("#valueDate").val() == '' && $("#endTime").val() == ''){
		return;
	}
	
	var data = {"valueDate":$("#valueDate").val(),"endTime":$("#endTime").val(),"term":holdingTime.val()};
    $.ajax(
		{url:"/products/isHoliday",
		data:data,
		type:'post',
		dataType:'json',
		success:function(data){
			if(data['status']==0){ // 不是节假日
				holdingTime.removeClass('font-red');
			}else{
				// 是节假日
				holdingTime.addClass('font-red');
			}
		}}
	);
}

// 添加持有时间
function addHoldingTime(button, value){
	var holdingTime = $(button.parentNode.parentNode).find('input[name$="holdingTime"]');
	var value = Number(holdingTime.val()) + value;
	if(value < 1){
		return;
	}
	holdingTime.val(value);
	checkHoliday( holdingTime );
}

</script>